<template>
  <div class="book-management">
    <h1>图书管理系统</h1>
    
    <!-- 搜索框 -->
    <el-input
      placeholder="输入关键字搜索"
      v-model="searchQuery"
      clearable
      style="width: 300px; margin-bottom: 20px;">
      <el-button slot="append" icon="el-icon-search"></el-button>
    </el-input>
    
    <!-- 添加图书表单 -->
    <el-card style="margin-bottom: 20px;">
      <el-form :model="newBook" :rules="rules" ref="bookForm" label-width="100px">
        <el-form-item label="书名" prop="title">
          <el-input v-model="newBook.title"></el-input>
        </el-form-item>
        <el-form-item label="作者" prop="author">
          <el-input v-model="newBook.author"></el-input>
        </el-form-item>
        <el-form-item label="库存数量" prop="copies">
          <el-input-number v-model="newBook.copies" :min="1"></el-input-number>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="addBook">添加图书</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 图书表格 -->
    <el-card>
      <el-table
        :data="filteredBooks"
        style="width: 100%"
        border
        stripe>
        <el-table-column
          prop="id"
          label="ID"
          width="80"
          sortable>
        </el-table-column>
        <el-table-column
          prop="title"
          label="书名"
          width="180">
        </el-table-column>
        <el-table-column
          prop="author"
          label="作者"
          width="180">
        </el-table-column>
        <el-table-column
          prop="copies"
          label="库存数量"
          sortable>
        </el-table-column>
        <el-table-column
          label="操作"
          width="120">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="danger"
              @click="deleteBook(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-wrapper">
        <el-pagination
          background
          layout="prev, pager, next"
          :total="filteredBooks.length"
          :page-size="10">
        </el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'BookManagement',
  data() {
    return {
      books: [],
      newBook: {
        title: '',
        author: '',
        copies: 1
      },
      searchQuery: '',
      rules: {
        title: [
          { required: true, message: '请输入书名', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        author: [
          { required: true, message: '请输入作者', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    filteredBooks() {
      return this.books.filter(book => {
        return book.title.toLowerCase().includes(this.searchQuery.toLowerCase()) || 
               book.author.toLowerCase().includes(this.searchQuery.toLowerCase())
      })
    }
  },
  created() {
    this.loadBooks()
  },
  methods: {
    loadBooks() {
      const savedBooks = localStorage.getItem('books')
      if (savedBooks) {
        this.books = JSON.parse(savedBooks)
      } else {
        // 初始数据
        this.books = [
          {"id": 1, "title": "Python编程", "author": "John Doe", "copies": 4},
          {"id": 2, "title": "历史的秘密", "author": "Jane Smith", "copies": 3},
          {"id": 3, "title": "宇宙探索", "author": "Emily Brown", "copies": 2},
          {"id": 4, "title": "健康生活", "author": "Mike Johnson", "copies": 5},
          {"id": 5, "title": "数学之美", "author": "Sarah Lee", "copies": 4}
        ]
        this.saveBooks()
      }
    },
    saveBooks() {
      localStorage.setItem('books', JSON.stringify(this.books))
    },
    addBook() {
      this.$refs.bookForm.validate((valid) => {
        if (valid) {
          const newId = this.books.length > 0 
            ? Math.max(...this.books.map(book => book.id)) + 1 
            : 1;
          
          this.books.push({
            id: newId,
            title: this.newBook.title,
            author: this.newBook.author,
            copies: this.newBook.copies
          });
          
          this.resetForm()
          this.saveBooks()
          this.$message.success('图书添加成功')
        }
      })
    },
    deleteBook(index, row) {
      this.$confirm('确认删除这本书吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const actualIndex = this.books.findIndex(book => book.id === row.id)
        this.books.splice(actualIndex, 1)
        this.saveBooks()
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })          
      })
    },
    resetForm() {
      this.$refs.bookForm.resetFields()
      this.newBook.copies = 1
    }
  }
}
</script>

<style scoped>
.book-management {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

h1 {
  margin-bottom: 20px;
  text-align: center;
  color: #303133;
}

.pagination-wrapper {
  margin-top: 20px;
  text-align: center;
}
</style>